#include <stdarg.h>

#include "head.h"

const uint8_t code picture[] = {
#include "picture_good_tran.inc"
};

int main() {
    lcd_init();
    lcd_cls();

    lcd_display(LEFT, picture);
    lcd_display(RIGHT, picture);

    PROGRAM_END;
}

void check_busy() {
    uint8_t temp;

    RS = 0;
    RW = 1;

    do {
        DATA_BUS = 0x00;
        E = 1;
        temp = DATA_BUS;
        E = 0;

    } while (0x80 & temp);
}

void lcd_write(uint8_t status, uint8_t datas) {
    check_busy();
    RS = status;
    RW = 0;
    E = 1;
    DATA_BUS = datas;
    E = 0;
}

void lcd_format(const char* fmt, ...) {
    uint8_t value;

    va_list args;
    va_start(args, fmt);

    while (*fmt) {
        value = va_arg(args, uint8_t);
        lcd_write(*fmt++ - 'C', value);
    }

    va_end(args);
}

void lcd_init() {
    DELAY(100);
    CS1 = 1;
    CS2 = 1;
    DELAY(100);

    lcd_format("CCCCC", LCD_OFF, PAGE_ADD, LINE_INIT, COL_ADD, LCD_ON);
}

void lcd_cls() {
    uint8_t i, j;

    CS1 = CS2 = 0;

    lcd_format("CC", PAGE_ADD, COL_ADD);

    for (i = 0; i < PAGE_SIZE; i++) {
        lcd_format("C", PAGE_ADD + i);

        for (j = 0; j < HEIGHT; j++) {
            lcd_format("CD", COL_ADD + j, 0x00);
        }
    }
}

void lcd_display(LCD_SIDE side, uint8_t code* bmp) {
    uint8_t i, j;

    uint8_t i_begin = side ? WIDTH / 2 : 0;
    uint8_t i_end = i_begin + WIDTH / 2;

    SWITCH_SCREEN(side);

    for (j = 0; j < PAGE_SIZE; j++) {
        lcd_format("CC", PAGE_ADD + j, COL_ADD);

        for (i = i_begin; i < i_end; i++) {
            lcd_format("D", bmp[WIDTH * j + i]);
        }
    }
}
